<?php

/**
 * The goal of this file is to allow developers a location
 * where they can overwrite core procedural functions and
 * replace them with their own. This file is loaded during
 * the bootstrap process and is called during the frameworks
 * execution.
 *
 * This can be looked at as a `master helper` file that is
 * loaded early on, and may also contain additional functions
 * that you'd like to use throughout your entire application
 *
 * @link: https://codeigniter4.github.io/CodeIgniter4/
 */

function view(string $name, array $data = [], array $options = []): string
{
    /**
     * @var CodeIgniter\View\View $renderer
     */

    $request = \Config\Services::request();
    $agent = $request->getUserAgent();

    if (IS_ADMIN) {
        $viewdir = 'admin/';
        $file = $name;
    } else if (defined('IS_INSTALL') && IS_INSTALL) {
        $viewdir = 'install/';
        $file = $name;
    } else {

        //前端模板public
        $viewdir = 'public/';
        if ((defined('SITE_MOBILE_OPEN') && SITE_MOBILE_OPEN) || (defined('SITE_MOBILE') && SITE_MOBILE) && $agent->isMobile()) {
            $file = 'mobile/' . $name;
            if (!is_file(APPPATH . 'Views/' . $file)) {
                $file = 'pc/' . $name;
            }
        } else {
            $file = 'pc/' . $name;
        }
    }
    $file = $viewdir . $file;

    //模板路径
    if (defined('MODDIR') && MODDIR) {
        $viewPath = APPSPATH . MODDIR . '/Views/';
    } else {
        $viewPath = null;
    }

    $renderer = Config\Services::renderer($viewPath);

    $saveData = null;
    if (array_key_exists('saveData', $options) && $options['saveData'] === true) {
        $saveData = (bool) $options['saveData'];
        unset($options['saveData']);
    }
    return $renderer->setData($data, 'raw')->render($file, $options, $saveData);
}

//应用目录
function get_module_dirs()
{
    $source_dir = APPSPATH;
    if ($fp = @opendir($source_dir)) {
        $filedata = array();
        $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        while (false !== ($file = readdir($fp))) {
            if ($file === '.' or $file === '..' or ($file[0] === '.') or !@is_dir($source_dir . $file)) {
                continue;
            }
            $filedata[] = $file;
        }
        closedir($fp);
        return $filedata;
    }
    return false;
}
